package com.example.xinyun.provider;

import com.example.xinyun.ResourceTable;
import com.example.xinyun.db.News;
import com.example.xinyun.domain.ImageUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.media.image.PixelMap;

import java.util.List;

public class NewsProvider extends BaseItemProvider {

    private List<News> newsList;
    private AbilitySlice abilitySlice;
    public NewsProvider(List<News> newsList, AbilitySlice abilitySlice) {
        this.newsList = newsList;
        this.abilitySlice = abilitySlice;
    }
    //返回ListContainer的大小
    @Override
    public int getCount() {
        return newsList==null?0:newsList.size();
    }

    //返回选中ListContainer的对象
    @Override
    public Object getItem(int i) {
        if (newsList!=null && i>=0 && i<newsList.size()){
            return newsList.get(i);
        }
        return null;
    }
    //返回选中ListContainer对象的id
    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
       final Component cpt;
       if(component==null){
           cpt = LayoutScatter.getInstance(this.abilitySlice).parse(ResourceTable.Layout_news_item, null, false);
            }
       else
           {
               cpt = component;
           }

       News newsItem = this.newsList.get(i);
       //设置ListContainer对象中每个控件的内容
       Text title = (Text) cpt.findComponentById(ResourceTable.Id_news_title);
       title.setText(newsItem.getTitle());
       Text author_name = (Text) cpt.findComponentById(ResourceTable.Id_author_name);
       author_name.setText(newsItem.getAuthorName());
       Text data = (Text) cpt.findComponentById(ResourceTable.Id_data);
       data.setText(newsItem.getDate());
       Image image=(Image) cpt.findComponentById(ResourceTable.Id_image);
       TaskDispatcher refreshUITask = abilitySlice.createParallelTaskDispatcher("",TaskPriority.DEFAULT);
       refreshUITask.syncDispatch(()->{
           PixelMap pixelMap = null;
           if (newsItem.getThumbnailPicS()!=null){
                pixelMap = ImageUtils.createPixelMap(newsItem.getThumbnailPicS());
           }
           PixelMap finalPixelMap = pixelMap;
           abilitySlice.getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
           @Override
           public void run() {
               //设置图片圆角
               image.setCornerRadius(30f);
               //Image组件填充位图数据，ui界面更新
               image.setPixelMap(finalPixelMap);
               finalPixelMap.release();
            }
          });

       });
           return cpt;
       }
}
